package com.sinosoft.weixin.utils.web;

import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.web.servlet.View;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.Map;

/**
 * 当文件被下载成功后会被删除
 */
public class FileDownloadView implements View {
  private String fileName;
  private File file;

  private boolean deleteFile = false;

  public FileDownloadView(File file) {
    this(file, file.getName());
  }

  public FileDownloadView(File file, String fileName) {
    this.fileName = fileName;
    this.file = file;
  }

  public void setDeleteFile(){
    deleteFile = true;
  }

  @Override
  public String getContentType() {
    return null;
  }

  @Override
  public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
    FileInputStream fis = null;
    try {
      fis = new FileInputStream(file);
      String name = URLEncoder.encode(fileName, "UTF-8");

      response.setHeader("Content-Length", String.valueOf(file.length()));
      response.setHeader("Content-Disposition", "attachment;filename=" + name);

      OutputStream out = response.getOutputStream();
      IOUtils.copy(fis, out);
    } catch (Exception ex) {
      response.setStatus(404);
      PrintWriter writer = new PrintWriter(response.getOutputStream());
      writer.println("文件不存在");
    } finally {
      IOUtils.closeQuietly(fis);
      if(deleteFile){
        FileUtils.deleteQuietly(file);
      }
    }
  }
}
